﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Driver;
using SJ.Platform.Common;
using SJ.Platform.EFCore.Model.FileManager;
using SJ.Platform.Extend.Response;
using SJ.Platform.File.DBOperation;

namespace SJ.Platform.Api.Controllers.FileManager
{
    /// <summary>
    /// 文件操作接口
    /// </summary>
    [Route(GlobalVariableHandle.Scope_Api + "/File")]
    [ApiController]
    [Authorize(GlobalVariableHandle.Scope_Api)]
    public class FileManagerController : ControllerBase
    {
        private readonly MongoOperation _mongoOperation;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mongoDatabase"></param>
        public FileManagerController(IMongoDatabase mongoDatabase)
        {
            _mongoOperation = new MongoOperation(mongoDatabase);
        }

        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="key"></param>
        /// <param name="files"></param>
        /// <returns></returns>
        [HttpPost("UploadFiles")]
        public async Task<IActionResult> UploadFiles([FromForm] string key, List<IFormFile> file)
        {
            List<UploadFile> list = new List<UploadFile>();
            try
            {
                foreach (var formFile in file)
                {
                    if (formFile.Length > 0)
                    {
                        Stream stream = formFile.OpenReadStream();
                        using (var memoryStream = new MemoryStream())
                        {
                            await stream.CopyToAsync(memoryStream);
                            byte[] bytes = memoryStream.ToArray();
                            string fileId = await _mongoOperation.Save(formFile.FileName, bytes);
                            list.Add(new UploadFile
                            {
                                FileName = formFile.FileName,
                                objectId = fileId
                            });
                        }
                    }
                }

                return Ok(ApiNormalResponse<List<UploadFile>>.SetResponse(ApiResponseStatus.Success, "上传成功", list)); // 返回成功的响应
            }
            catch (Exception ex)
            {
                return BadRequest(ApiNormalResponse<List<UploadFile>>.SetResponse(ApiResponseStatus.BadRequest, "上传失败：" + ex.Message, list));
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="objectId"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        [HttpGet("DownloadFile/{objectId}/{fileName}")]
        public async Task<IActionResult> DownloadFile(string objectId, string fileName)
        {
            // 从 MongoDB 获取文件数据
            byte[] fileData = await _mongoOperation.DownLoad(objectId);

            if (fileData == null)
            {
                return NotFound(ApiNormalResponse<string>.SetResponse(ApiResponseStatus.NoData, "文件未找到", null));
            }

            return File(fileData, "application/octet-stream", fileName);
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="objectId"></param>
        /// <returns></returns>
        [HttpGet("DeleteFile/{objectId}")]
        public async Task<IActionResult> DeleteFile(string objectId)
        {
            try
            {
                // 从 MongoDB 获取文件数据
                bool result = await _mongoOperation.Delete(objectId);

                return Ok(ApiNormalResponse<bool>.SetResponse(result ? ApiResponseStatus.Success : ApiResponseStatus.BadRequest, "删除文件" + (result ? "成功" : "失败"), result));
            }
            catch (Exception ex)
            {
                return BadRequest(ApiNormalResponse<bool>.SetResponse(ApiResponseStatus.BadRequest, "删除文件失败：" + ex.Message, false));
            }
        }
    }
}
